package controller;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import util.AjaxResultDto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping ("/")
public class EditController {
	/**
	 * edit(跳转项目编辑页面)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param request
	 * @param response
	 * @return
	 *ModelAndView
	 * @exception
	 * @since  1.0.0
	*/
	@RequestMapping ("edit")  
    public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) {  
       ModelAndView modelAndView = new ModelAndView();  
       //1.获取项目id
       String projectId = request.getParameter("projectId");
       modelAndView.addObject("projectId", projectId);
       modelAndView.setViewName( "edit.jsp" );  
       return modelAndView;  
    }  
	
	/**
	 * uploadbackimg(上传图片 )
	 * (这里描述这个方法适用条件 – 可选)
	 * @param request
	 * @param response
	 * @return
	 *ModelAndView
	 * @exception
	 * @since  1.0.0
	*/
	@RequestMapping("/uploadbackimg")
	public void uploadbackimg(HttpServletRequest req, HttpServletResponse res) throws Exception {
		JSONObject imgInfo = new JSONObject();//图片信息
		String newFileName = "";//存入数据库的文件名
		String oldFileName = "";//前台上传图片原文件名
		req.setCharacterEncoding("utf-8");
		if (req.getParameter("errorCode") != null) {
			res.sendError(Integer.parseInt(req.getParameter("errorCode")), req.getParameter("errorMessage"));
			return;
		}
		if (req.getHeader("Content-Type") != null && req.getHeader("Content-Type").startsWith("multipart/form-data")) {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iterator = upload.getItemIterator(req);
			//1.遍历图片
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				//2.获取图片存放路径
				String userbackimgPath = req.getSession().getServletContext().getRealPath("/lib/images/UserbackImg/");
				File userbackimgFile = new File(userbackimgPath);
				if (!userbackimgFile.exists()) { // 如果不存在，则新建文件夹
					userbackimgFile.mkdirs();
				}
				oldFileName = item.getName();
				newFileName = UUID.randomUUID().toString().replace("-", "") + "_" + item.getName(); // 给上传文件重命名
				File uploadFile = new File(userbackimgPath + "/" + newFileName);
				//3.保存图片
				InputStream stream = item.openStream();
				OutputStream os = new FileOutputStream(uploadFile);
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
				  os.write(buffer, 0, bytesRead);
				}
				BufferedImage img = ImageIO.read(uploadFile);
				imgInfo.put("fileName", oldFileName);
				imgInfo.put("width", img.getWidth());
				imgInfo.put("height", img.getHeight());
				imgInfo.put("filesrc", newFileName);
				os.close();
			}
		} 
		AjaxResultDto dto = new AjaxResultDto();
		dto.setData(imgInfo);
		//3.返回结果
		PrintWriter out = res.getWriter();
		out.print(JSON.toJSONString(dto));
		out.flush();
		out.close();
	}
	
	protected int size(InputStream stream) {
		int length = 0;
		try {
			byte[] buffer = new byte[2048];
			int size;
			while ((size = stream.read(buffer)) != -1) {
				length += size;
//				 for (int i = 0; i < size; i++) {
//				 System.out.print((char) buffer[i]);
//				 }
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return length;

	}

	protected String read(InputStream stream) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		try {
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
			}
		}
		return sb.toString();
	}
	
}
